package pers.zb.center.web.boss.controller.fileprint;

import com.lowagie.text.pdf.BaseFont;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;
import pers.zb.center.web.boss.controller.fileprint.util.FreemarkerUtils;
import pers.zb.center.web.boss.controller.fileprint.vo.LocationVo;
import pers.zb.center.web.boss.controller.fileprint.vo.OrderInfo;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ========================================需要注意的地方================================================
 *
 * 在ftl页面中，如果需要空格，不能使用&nbsp;这个字符，需要使用&#160;这个字符。
 * 原因是：&nbsp;是html中的空格的转义，而&#160;是XSL中的。XSL并不认识&nbsp;
 *
 * ========================================需要注意的地方================================================
 */

/**
 * PDF打印
 * @author zhoubang
 *
 */
@Controller
@RequestMapping("/pdf")
public class PDFPrintController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 进入PDF打印页面
     */
    @RequestMapping("/print/view")
    @RequiresPermissions("pdf:file:print")
    public String toPdfPrintView(HttpServletRequest request, HttpServletResponse response, ModelMap map) {
        return "/file_print/pdf_print";
    }

    @RequestMapping(value = "/print")
    public void send(HttpServletRequest request, HttpServletResponse response,boolean single) throws Exception {
        logger.debug("pdf文件打印");

        String path = request.getContextPath();
        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
        Map<String, Object> root = new HashMap<>();
        root.put("base", basePath);
        root.put("orderInfos", getInfoList(single));
        root.put("sendlvs", getSendLocationList(single));
        root.put("receiverlvs", getReceiverLocationList(single));
        root.put("customerNames", getCustomerNames(single));

        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "attachment;filename=print.pdf");//print.pdf 是生成的文件名称

        try {
            String frontPath = new ClassPathResource("../printTemplete/msyh.ttf").getFile().getAbsolutePath();
            String templateString = FileUtils.readFileToString(new ClassPathResource("../printTemplete/ems.ftl").getFile(),"UTF-8");//加载读取模板内容
            //调用具体打印pdf方法
            printPdf(root, templateString, frontPath, response.getOutputStream());
            response.getOutputStream().flush();
            response.getOutputStream().close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 打印PDF具体代码
     *
     * 创建日期：2016年7月22日 下午1:07:38
     * 操作用户：zhoubang
     *
     * @param root
     * @param templateString
     * @param frontPath
     * @param outputStream
     */
    private void printPdf(Map<String, Object> root, String templateString, String frontPath, ServletOutputStream outputStream) {
        String ttt = null;
        try {
            ttt = FreemarkerUtils.process(templateString, root);
            ITextRenderer iTextRenderer = new ITextRenderer();
            iTextRenderer.setDocumentFromString(ttt);
            if (StringUtils.isNotEmpty(frontPath)) {
                ITextFontResolver fontResolver = iTextRenderer.getFontResolver();
                fontResolver.addFont(frontPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            }
            iTextRenderer.layout();
            iTextRenderer.createPDF(outputStream);
        } catch (Exception e) {
            logger.info("打印ems模板单出错" + e.getMessage());
        }
        if (ttt == null) {
            logger.info("打印ems模板单出错,生成模板为空");
            return;
        }
    }

    /**
     * 模拟数据
     * @return
     */
    private static List<OrderInfo> getInfoList(boolean single){
        List<OrderInfo> orderInfos = new ArrayList<OrderInfo>();
        //模拟数据
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setTrackNo("8648722123456");
        orderInfo.setSendName("张三");
        orderInfo.setSendAddress("上海市普陀区武宁路");
        orderInfo.setReceiverName("李四");
        orderInfo.setReceiverTel("15988888888");
        orderInfo.setReceiverAddress("江苏省徐州市睢宁县");
        orderInfo.setWeight(2000);
        orderInfo.setOrderNo("20160722123456");
        orderInfo.setProductName("衣物");
        orderInfo.setProNameRemark("备注什么好呢");
        orderInfos.add(orderInfo);

        if(single == false){
            OrderInfo orderInfo2 = new OrderInfo();
            orderInfo2.setTrackNo("2568745498799");
            orderInfo2.setSendName("李白");
            orderInfo2.setSendAddress("上海市徐汇区田林路");
            orderInfo2.setReceiverName("武则天");
            orderInfo2.setReceiverTel("18766666666");
            orderInfo2.setReceiverAddress("安徽省萧县xxx街123号");
            orderInfo2.setWeight(1500);
            orderInfo2.setOrderNo("20171222987456");
            orderInfo2.setProductName("食品");
            orderInfo2.setProNameRemark("包装好，尽快发货！");
            orderInfos.add(orderInfo2);
        }
        return orderInfos;
    }
    /**
     * 模拟数据
     * @return
     */
    private static List<LocationVo> getSendLocationList(boolean single){
        List<LocationVo> locationVos = new ArrayList<LocationVo>();
        LocationVo vo = new LocationVo();
        vo.setProvinceName("上海市");
        vo.setCityName("上海市");
        vo.setAreaName("徐汇区");
        locationVos.add(vo);

        if(single == false){
            LocationVo vo2 = new LocationVo();
            vo2.setProvinceName("上海市");
            vo2.setCityName("上海市");
            vo2.setAreaName("嘉定区");
            locationVos.add(vo2);
        }
        return locationVos;
    }
    /**
     * 模拟数据
     * @return
     */
    private static List<LocationVo> getReceiverLocationList(boolean single){
        List<LocationVo> locationVos = new ArrayList<LocationVo>();
        LocationVo vo = new LocationVo();
        vo.setProvinceName("上海市");
        vo.setCityName("上海市");
        vo.setAreaName("徐汇区");
        locationVos.add(vo);

        if(single == false){
            LocationVo vo2 = new LocationVo();
            vo2.setProvinceName("上海市");
            vo2.setCityName("上海市");
            vo2.setAreaName("静安区");
            locationVos.add(vo2);
        }
        return locationVos;
    }
    /**
     * 模拟数据
     * @return
     */
    private static List<String> getCustomerNames(boolean single){
        List<String> customerNames = new ArrayList<String>();
        customerNames.add("上海玉皇大帝有限公司");

        if(single == false){
            customerNames.add("上海无量神功有限公司");
        }
        return customerNames;
    }

}
